package org.kits.activiti6.demo;

import org.activiti.bpmn.model.*;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.*;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.repository.DeploymentBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.jar.JarInputStream;
import java.util.zip.ZipInputStream;

/**
 * @author SKyOne
 * @create 2020-06-13 8:22
 */
public class DemoMain {

    private static final Logger logger = LoggerFactory.getLogger(DemoMain.class);

    private static void getDefaultProcessEngine(){
        // 1. 创建流程引擎
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
        // 2. 部署流程定义文件
        ProcessEngine processEngine = cfg.buildProcessEngine();

        // 3. 启动流程

        // 4. 处理流程任务

        String name = processEngine.getName();
        String version = ProcessEngine.VERSION;
        logger.debug("流程引擎名称{},版本{}",name,version);
        logger.info("流程引擎名称{},版本{}",name,version);
        System.out.println("流程引擎名称："+name);
        System.out.println("流程版本："+version);

        // 获取各个业务组件实例
        RepositoryService repositoryService = processEngine.getRepositoryService();
        RuntimeService runtimeService = processEngine.getRuntimeService();
        TaskService taskService = processEngine.getTaskService();
        IdentityService identityService = processEngine.getIdentityService();
        ManagementService managementService = processEngine.getManagementService();
        HistoryService historyService = processEngine.getHistoryService();
        DynamicBpmnService dynamicBpmnService = processEngine.getDynamicBpmnService();


        Map<String, ProcessEngine> engines = ProcessEngines.getProcessEngines();
        System.out.println("流程数："+engines.size());


        // 5. 关闭流程引擎
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        processEngine.close();
    }

    private static void getUserDefinistionProcessEngine(String filePath){
        // 1. 创建流程引擎
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource(filePath);
        // 2. 部署流程定义文件
        ProcessEngine processEngine = cfg.buildProcessEngine();
        String name = processEngine.getName();
        String version = ProcessEngine.VERSION;
        logger.debug("流程引擎名称{},版本{}",name,version);
        logger.info("流程引擎名称{},版本{}",name,version);
        System.out.println("流程引擎名称："+name);
        System.out.println("流程版本："+version);

        Map<String, ProcessEngine> engines = ProcessEngines.getProcessEngines();
        System.out.println("流程数："+engines.size());

    }

    static void UserGroupManage(){
        // 1. 创建流程引擎
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration();
        // 2. 部署流程定义文件
        ProcessEngine processEngine = cfg.buildProcessEngine();

        ProcessEngine engine = ProcessEngines.getDefaultProcessEngine();
        // 得到身份服务组件实例
        IdentityService identityService = engine.getIdentityService();
        // 生成UUID
        String genId = UUID.randomUUID().toString();
        Group group = identityService.newGroup(genId);
        group.setName("经理组");
        group.setType("manager");
        // 保存Group到数据库
        identityService.saveGroup(group);

        // 查询组信息
        Group data = identityService.createGroupQuery().groupId(genId).singleResult();
        System.out.println(data.getId()+",Name=>"+data.getName()+",Type=>"+data.getType());

        // 查询并排序
        List<Group> list = identityService.createGroupQuery().orderByGroupId().asc().list();
        System.out.println("listSize=>"+list.size());
        for(Group g : list){
            System.out.println("Name=>"+g.getName());
        }

        // 原生sql
       /* list = identityService.createNativeGroupQuery().sql("select * from act_id_group where name = #{name}")
                .parameter("name","GroupId")
                .list();
        System.out.println("listSize=>"+list.size());
        for(Group g : list){
            System.out.println("Name=>"+g.getName());
        }*/

        // 删除组
        identityService.deleteGroup(genId);
        System.out.println("删除后组："+identityService.createGroupQuery().count());
    }

    static void UserManage(){
        ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
        ProcessEngine engine = processEngineConfiguration.buildProcessEngine();

        IdentityService identityService = engine.getIdentityService();
        String uuid = UUID.randomUUID().toString();
        User user = identityService.newUser(uuid);
        // 设置用户属性
        user.setEmail("test@test.com");
        user.setFirstName("test");
        user.setId(uuid);
        user.setLastName("admin");
        user.setPassword("test");

        // 保存用户信息
        identityService.saveUser(user);

        // 查询用户，by id
        user = identityService.createUserQuery().userId(uuid).singleResult();
        System.out.println("User info=>"+user.getEmail()+","+user.getPassword());
    }

    /**
     * 对于表：
     * select * from act_ge_bytearray;
     * select * from act_re_deployment;
     * @param filePath
     */
    static void deploy_process(String filePath){
        // 1. 创建流程引擎
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("activiti.cfg.xml");
        // 2. 部署流程定义文件
        ProcessEngine processEngine = cfg.buildProcessEngine();
        // 3. 获取部署对象
        RepositoryService repositoryService = processEngine.getRepositoryService();
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(filePath));

            // 保存图片资源
            DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
//            deploymentBuilder.addInputStream("qingjia",inputStream);

            // 保存zip资源
            ZipInputStream zipInputStream = new ZipInputStream(inputStream);

            // 执行部署方法
            deploymentBuilder.addZipInputStream(zipInputStream);
            deploymentBuilder.deploy();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    static void createProcessByCode(){
        // 1. 创建流程引擎
        ProcessEngineConfiguration cfg = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("activiti.cfg.xml");
        // 2. 部署流程定义文件
        ProcessEngine processEngine = cfg.buildProcessEngine();
        RepositoryService repositoryService = processEngine.getRepositoryService();
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
        deploymentBuilder.addBpmnModel("MyCodeProcess",createProcessModel())
                .name("MyCodeDeploy")
                .deploy();
    }

    static BpmnModel createProcessModel(){
        BpmnModel model = new BpmnModel();
        Process process = new Process();
        model.addProcess(process);

        process.setId("myProcess");
        process.setName("myProcess");

        // 开始事件
        StartEvent startEvent = new StartEvent();
        startEvent.setId("startEvent");
        process.addFlowElement(startEvent);
        // 用户任务
        UserTask userTask = new UserTask();
        userTask.setName("userTask");
        userTask.setId("userTask");
        process.addFlowElement(userTask);
        // 结束事件
        EndEvent endEvent = new EndEvent();
        endEvent.setId("endEvent");;
        endEvent.setName("endEvent");
        process.addFlowElement(endEvent);
        // 添加流程顺序
        process.addFlowElement(new SequenceFlow("startEvent","userTask"));
        process.addFlowElement(new SequenceFlow("userTask","endTask"));

        return model;
    }

    public static void main(String[] args) {
        System.out.println("Start");
//        getDefaultProcessEngine();
//        UserGroupManage();
//        UserManage();
        String filePath = "D:\\Labs\\Learning\\learning-something\\learn-activiti6\\src\\main\\resources\\";
//        deploy_process(filePath+"first.zip");

        createProcessByCode();

        System.out.println("End.");

    }
}
